import { Modal, Form, Input, Button, Space, message, Radio, Select } from 'antd'
import http from '../api/http'
import type { IHealthPlan } from '../types/healthplan'
import type { FormInstance } from 'antd'
import { useEffect } from 'react'
import dayjs from 'dayjs'

// 健康计划类型选项（Typeid对应数值）
const planTypeOptions = [
  { id: 1, name: '基础保健' },
  { id: 2, name: '疾病康复' },
  { id: 3, name: '专项训练' },
  { id: 4, name: '营养调理' }
]

// 状态选项（State对应数值）
const stateOptions = [
  { id: 1, name: '已启用' },
  { id: 0, name: '未启用' }
]

interface Props {
  isModalOpen: boolean
  handleCancel: () => void
  onSuccess: () => void
}

const Add: React.FC<Props> = ({ isModalOpen, handleCancel, onSuccess }) => {
  const [form] = Form.useForm<FormInstance<IHealthPlan>>()

  // 重置表单
  useEffect(() => {
    if (!isModalOpen) {
      form.resetFields()
    }
  }, [form, isModalOpen])

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        // 构建健康计划提交数据
        const submitData: IHealthPlan = {
            code:'',
            title:'',
           keywords:'',
           typeid:0,
           content:'',
           state:0,
           remark:'',
          ...values,
          id: 0,
          createtime: new Date(),
          updatetime: new Date()
        }

        // 调用健康计划添加接口
        http.post('healthplan', submitData)
          .then(() => {
            message.success('添加成功')
            handleCancel()
            form.resetFields()
            onSuccess()
          })
          .catch(err => {
            console.error('添加失败:', err)
            message.error('添加失败，请重试')
          })
      })
      .catch(info => {
        console.log('表单验证失败:', info)
        message.warning('请完善必填字段')
      })
  }

  return (
    <Modal
      title="添加健康计划"
      open={isModalOpen}
      onCancel={handleCancel}
      centered
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          确认添加
        </Button>
      ]}
      width={700}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          Typeid: 1,  // 默认基础保健
          State: 1     // 默认已启用
        }}
      >
        <Space style={{ width: '100%' }}>
          <Form.Item
            name="code"
            label="计划编码"
            rules={[
              { required: true, message: '请输入计划编码' },
              { pattern: /^[A-Za-z0-9]+$/, message: '编码只能包含字母和数字' }
            ]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Input placeholder="如：JH0001" />
          </Form.Item>

          <Form.Item
            name="Title"
            label="计划标题"
            rules={[
              { required: true, message: '请输入计划标题' },
              { min: 2, max: 50, message: '标题长度2-50字符' }
            ]}
            style={{ flex: 2 }}
          >
            <Input placeholder="请输入健康计划标题" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="Typeid"
            label="计划类型"
            rules={[{ required: true, message: '请选择计划类型' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Select placeholder="选择计划类型">
              {planTypeOptions.map(type => (
                <Select.Option key={type.id} value={type.id}>
                  {type.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="State"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              {stateOptions.map(state => (
                <Radio key={state.id} value={state.id}>
                  {state.name}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
        </Space>

        <Form.Item
          name="Keywords"
          label="关键词"
          rules={[
            { required: true, message: '请输入关键词' },
            { min: 2, message: '关键词至少2个字符' }
          ]}
        >
          <Input placeholder="多个关键词用逗号分隔（如：健身,养生）" />
        </Form.Item>

        <Form.Item
          name="Content"
          label="计划内容"
          rules={[
            { required: true, message: '请输入计划内容' },
            { min: 10, message: '内容至少10个字符' }
          ]}
        >
          <Input.TextArea 
            rows={6} 
            placeholder="请详细描述健康计划的具体内容、执行步骤等" 
          />
        </Form.Item>

        <Form.Item
          name="Remark"
          label="备注"
        >
          <Input.TextArea 
            rows={3} 
            placeholder="请输入补充说明（可选）" 
          />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export { Add }